from .base_handler import BaseRequestHandler


class SUTPageManageHandler(BaseRequestHandler):
    """被测系统 页面 管理"""
    async def get_default(self):
        node_level = self.get_argument('node_level', '')
        parent_node_id = self.get_argument('parent_node_id', '')
        data = await self.mdb.query_by_dict(
            table='test_element_node',
            where={'node_level': node_level, 'parent_node_id': parent_node_id}
            # order_by='node_name'
        )
        self.success_data = data

    async def post_addNode(self):
        """添加 页面"""
        d = {
            'node_name': self.escape_string(self.request_json['node_name']),
            'parent_node_id': self.request_json['parent_node_id'],
            'node_level': self.request_json['node_level']
        }
        node_id = await self.mdb.insert_by_dict('test_element_node', get_last_id=True, data=d)
        d['id'] = node_id
        self.success_data = d

    async def post_editNode(self):
        """修改 页面 名称"""
        node_id = self.request_json['id']
        node_name = self.escape_string(self.request_json['node_name'])
        await self.mdb.update_by_dict(
            table='test_element_node',
            colv={'node_name': self.escape_string(node_name)},
            where={'id': node_id}
        )

    async def post_changeElementsPage(self):
        page_id = self.get_argument('pageId')
        elements = self.request_json
        for element_id in elements:
            await self.mdb.update_by_dict(
                table='test_element',
                colv={'page_id': page_id},
                where={'id': element_id}
            )

    async def post_delNode(self):
        """删除 系统节点、页面节点"""
        node_id = self.request_json['id']
        if int(node_id) == 0:
            raise Exception('此节点不能删除！')
        await self.mdb.delete_by_dict(
            table='test_element_node',
            where={'id': node_id, 'parent_node_id': node_id},
            where_logic='or'
        )
